package web_api

import (
	"github.com/gin-gonic/gin"
	"net/http"
	"platon-tools/go-service/common/constant"
	"platon-tools/go-service/common/util"
	go_logger "platon-tools/go-service/go-logger"
	"platon-tools/go-service/module"
	"platon-tools/go-service/module/model"
	"strconv"
	"time"
)

type UserResponse struct {
	Id             int    `json:"id"`
	UserName       string `json:"user_name"`
	Nickname       string `json:"nickname"`
	Phone          string `json:"phone"`
	OrgId          int    `json:"org_id"`
	OrgName        string `json:"org_name"`
	RoleId         int    `json:"role_id"`
	RoleName       string `json:"role_name"`
	Avatar         string `json:"avatar"`
	Email          string `json:"email"`
	Status         int    `json:"status"`
	MenuPerm       []int  `json:"menu_perm,omitempty"`
	NodePerm       []int  `json:"node_perm,omitempty"`
	RoleArea       []int  `json:"role_area,omitempty"`
	SessionId      string `json:"session_id,omitempty"`
	CreateUserName string `json:"create_user_name"`
	CreateTime     string `json:"create_time"`
	UpdateUserName string `json:"update_user_name"`
	UpdateTime     string `json:"update_time"`
}

// 登陆
func (api *HttpApi) Login(c *gin.Context) {

	var err error
	var result UserResponse

	username := c.PostForm("user_name")
	password := c.PostForm("user_password")

	r := api.service.ModuleByName("MYSQLDB")
	if db, ok := r.(*module.MysqlDB); ok {
		var user model.SysUser
		wherePhone := map[string]interface{}{
			"phone": username,
		}
		whereEmail := map[string]interface{}{
			"email": username,
		}
		err = db.Table(model.SysUserTable).Where(wherePhone).Or(whereEmail).Not("status", 3).First(&user).Error
		if err != nil {
			c.JSON(http.StatusOK, util.FailResponse(constant.ERROR_CODE_1100, constant.ERROR_MESSAGE_1100))
			return
		}
		if user.UserPassword != password {
			c.JSON(http.StatusOK, util.FailResponse(constant.ERROR_CODE_1101, constant.ERROR_MESSAGE_1101))
			return
		}
		if user.Status == constant.USER_STATUS_FREESE {
			c.JSON(http.StatusOK, util.FailResponse(constant.ERROR_CODE_1102, constant.ERROR_MESSAGE_1102))
			return
		}

		// 存储session
		userId := util.ToString(user.Id)
		session := util.GenerateSessionKey(userId)
		s := api.service.ModuleByName("REDIS")
		if redis, ok := s.(*module.RedisDB); ok {
			err = redis.SetSession(session, userId+"|"+username)
			if err != nil {
				go_logger.Logger.Error("login 存储session失败, user_id: " + userId)
				c.JSON(http.StatusOK, util.FailResponse(constant.ERROR_CODE_1001, constant.ERROR_MESSAGE_1001))
				return
			}
		}

		// 获取角色信息
		var role model.SysRole
		err = db.Table(model.SysRoleTable).Where(map[string]interface{}{"id": user.RoleId}).First(&role).Error
		if err != nil {
			go_logger.Logger.Error("login 获取角色信息失败, user_id: " + userId)
			c.JSON(http.StatusOK, util.FailResponse(constant.ERROR_CODE_1001, constant.ERROR_MESSAGE_1001))
			return
		}

		// 拼接结果
		result.Id = user.Id
		result.UserName = user.UserName
		result.Nickname = user.Nickname
		result.Avatar = user.Avatar
		result.Email = user.Email
		result.Phone = user.Phone
		result.RoleId = user.RoleId
		result.RoleName = role.RoleName
		result.OrgId = user.OrgId
		result.OrgName = user.OrgName
		result.NodePerm = role.GetNodePerm()
		result.MenuPerm = role.GetMenuPerm()
		result.RoleArea = role.GetRoleArea()
		result.CreateUserName = user.CreateUserName
		result.UpdateUserName = user.UpdateUserName
		result.CreateTime = user.CreateTime.Format(constant.DATE_FORMAT)
		result.UpdateTime = user.UpdateTime.Format(constant.DATE_FORMAT)
		result.SessionId = session

		c.JSON(http.StatusOK, util.SuccessResponse(result))
		return
	}
}

// 注销登陆
func (api *HttpApi) Logout(c *gin.Context) {

	var err error

	sessionId := c.GetHeader("session_id")
	if redis, ok := api.service.ModuleByName("REDIS").(*module.RedisDB); ok {
		err = redis.Del(sessionId)
		if err != nil {
			go_logger.Logger.Error("logout 删除session失败")
			c.JSON(http.StatusOK, util.FailResponse(constant.ERROR_CODE_1001, constant.ERROR_MESSAGE_1001))
			return
		}

		c.JSON(http.StatusOK, util.SuccessResponse(nil))
		return
	}
}

// 本人用户详情
func (api *HttpApi) MyselfDetail(c *gin.Context) {

	var result UserResponse

	userId, exist := c.Get("login_id")
	if !exist || userId == "" {
		c.JSON(http.StatusOK, util.FailResponse(constant.ERROR_CODE_1103, constant.ERROR_MESSAGE_1103))
		return
	}

	r := api.service.ModuleByName("MYSQLDB")
	if db, ok := r.(*module.MysqlDB); ok {
		var user model.SysUser
		where := map[string]interface{}{
			"id": userId,
		}
		err := db.Table(model.SysUserTable).Where(where).First(&user).Error
		if err != nil {
			go_logger.Logger.Error(err.Error())
			c.JSON(http.StatusOK, util.FailResponse(constant.ERROR_CODE_1001, constant.ERROR_MESSAGE_1001))
			return
		}

		// 获取角色信息
		var role model.SysRole
		err = db.Table(model.SysRoleTable).Where(map[string]interface{}{"id": user.RoleId}).First(&role).Error
		if err != nil {
			go_logger.Logger.Error("detail 获取角色信息失败, user_id: " + util.ToString(userId))
			c.JSON(http.StatusOK, util.FailResponse(constant.ERROR_CODE_1001, constant.ERROR_MESSAGE_1001))
			return
		}

		// 拼接结果
		result.Id = user.Id
		result.UserName = user.UserName
		result.Nickname = user.Nickname
		result.Avatar = user.Avatar
		result.Email = user.Email
		result.Phone = user.Phone
		result.RoleId = user.RoleId
		result.RoleName = role.RoleName
		result.OrgId = user.OrgId
		result.OrgName = user.OrgName
		result.NodePerm = role.GetNodePerm()
		result.MenuPerm = role.GetMenuPerm()
		result.RoleArea = role.GetRoleArea()
		result.CreateUserName = user.CreateUserName
		result.UpdateUserName = user.UpdateUserName
		result.CreateTime = user.CreateTime.Format(constant.DATE_FORMAT)
		result.UpdateTime = user.UpdateTime.Format(constant.DATE_FORMAT)

		c.JSON(http.StatusOK, util.SuccessResponse(result))
		return
	}
}

// 用户详情
func (api *HttpApi) UserDetail(c *gin.Context) {

	var result UserResponse

	userId := c.PostForm("user_id")
	if userId == "" {
		c.JSON(http.StatusOK, util.FailResponse(constant.ERROR_CODE_1003, "user_id不能为空"))
		return
	}

	r := api.service.ModuleByName("MYSQLDB")
	if db, ok := r.(*module.MysqlDB); ok {
		var user model.SysUser
		where := map[string]interface{}{
			"id": userId,
		}
		err := db.Table(model.SysUserTable).Where(where).First(&user).Error
		if err != nil {
			go_logger.Logger.Error(err.Error())
			c.JSON(http.StatusOK, util.FailResponse(constant.ERROR_CODE_1001, constant.ERROR_MESSAGE_1001))
			return
		}

		// 获取角色信息
		var role model.SysRole
		err = db.Table(model.SysRoleTable).Where(map[string]interface{}{"id": user.RoleId}).First(&role).Error
		if err != nil {
			go_logger.Logger.Error("detail 获取角色信息失败, user_id: " + util.ToString(userId))
			c.JSON(http.StatusOK, util.FailResponse(constant.ERROR_CODE_1001, constant.ERROR_MESSAGE_1001))
			return
		}

		// 拼接结果
		result.Id = user.Id
		result.UserName = user.UserName
		result.Nickname = user.Nickname
		result.Avatar = user.Avatar
		result.Email = user.Email
		result.Phone = user.Phone
		result.RoleId = user.RoleId
		result.RoleName = role.RoleName
		result.OrgId = user.OrgId
		result.OrgName = user.OrgName
		result.NodePerm = role.GetNodePerm()
		result.MenuPerm = role.GetMenuPerm()
		result.RoleArea = role.GetRoleArea()
		result.CreateUserName = user.CreateUserName
		result.UpdateUserName = user.UpdateUserName
		result.CreateTime = user.CreateTime.Format(constant.DATE_FORMAT)
		result.UpdateTime = user.UpdateTime.Format(constant.DATE_FORMAT)

		c.JSON(http.StatusOK, util.SuccessResponse(result))
		return
	}
}

// 修改密码
func (api *HttpApi) EditPassword(c *gin.Context) {

	var err error

	userId, exist := c.Get("login_id")
	if !exist || userId == "" {
		c.JSON(http.StatusOK, util.FailResponse(constant.ERROR_CODE_1103, constant.ERROR_MESSAGE_1103))
		return
	}
	// 原始密码
	oldPassword := c.PostForm("old_password")
	if oldPassword == "" {
		c.JSON(http.StatusOK, util.FailResponse(constant.ERROR_CODE_1003, "请填写原密码"))
		return
	}
	// 新密码
	newPassword := c.PostForm("new_password")
	if newPassword == "" {
		c.JSON(http.StatusOK, util.FailResponse(constant.ERROR_CODE_1003, "请填写新密码"))
		return
	}

	r := api.service.ModuleByName("MYSQLDB")
	if db, ok := r.(*module.MysqlDB); ok {
		var user model.SysUser
		where := map[string]interface{}{
			"id": userId,
		}
		err = db.Table(model.SysUserTable).Where(where).First(&user).Error
		if err != nil {
			go_logger.Logger.Error(err.Error())
			c.JSON(http.StatusOK, util.FailResponse(constant.ERROR_CODE_1001, constant.ERROR_MESSAGE_1001))
			return
		}

		if user.UserPassword != oldPassword {
			c.JSON(http.StatusOK, util.FailResponse(constant.ERROR_CODE_1302, constant.ERROR_MESSAGE_1302))
			return
		}

		user.UserPassword = newPassword
		user.UpdateTime = time.Now()
		user.UpdateUserName = user.UserName

		err = db.Table(model.SysUserTable).Save(&user).Error
		if err != nil {
			go_logger.Logger.Error(err.Error())
			c.JSON(http.StatusOK, util.FailResponse(constant.ERROR_CODE_1002, constant.ERROR_MESSAGE_1002))
			return
		}

		c.JSON(http.StatusOK, util.SuccessResponse(nil))
		return
	}
}

// 重置密码
func (api *HttpApi) ResetPassword(c *gin.Context) {

	var err error

	loginName, exist := c.Get("login_name")
	if !exist || loginName == "" {
		c.JSON(http.StatusOK, util.FailResponse(constant.ERROR_CODE_1103, constant.ERROR_MESSAGE_1103))
		return
	}

	resetUserId := c.PostForm("user_id")

	r := api.service.ModuleByName("MYSQLDB")
	if db, ok := r.(*module.MysqlDB); ok {
		var user model.SysUser
		where := map[string]interface{}{
			"id": resetUserId,
		}
		err = db.Table(model.SysUserTable).Where(where).First(&user).Error
		if err != nil {
			go_logger.Logger.Error(err.Error())
			c.JSON(http.StatusOK, util.FailResponse(constant.ERROR_CODE_1001, constant.ERROR_MESSAGE_1001))
			return
		}

		user.UserPassword = constant.DEFAULT_PASSWORD
		user.UpdateTime = time.Now()
		user.UpdateUserName = util.ToString(loginName)

		err = db.Table(model.SysUserTable).Save(&user).Error
		if err != nil {
			go_logger.Logger.Error(err.Error())
			c.JSON(http.StatusOK, util.FailResponse(constant.ERROR_CODE_1002, constant.ERROR_MESSAGE_1002))
			return
		}

		c.JSON(http.StatusOK, util.SuccessResponse(nil))
		return
	}
}

type AddUserRequest struct {
	UserName     string `form:"user_name" json:"user_name"`
	Nickname     string `form:"nickname" json:"nickname"`
	RoleId       int    `form:"role_id" json:"role_id" binding:"required"`
	OrgId        int    `form:"org_id" json:"org_id"`
	OrgName      string `form:"org_name" json:"org_name"`
	UserPassword string `form:"user_password" json:"user_password"`
	Phone        string `form:"phone" json:"phone" binding:"required"`
	Email        string `form:"email" json:"email" binding:"required"`
}

// 新建用户
func (api *HttpApi) AddUser(c *gin.Context) {

	var err error

	userId, exist := c.Get("login_id")
	if !exist || userId == "" {
		c.JSON(http.StatusOK, util.FailResponse(constant.ERROR_CODE_1103, constant.ERROR_MESSAGE_1103))
		return
	}
	userName, exist := c.Get("login_name")
	if !exist || userName == "" {
		c.JSON(http.StatusOK, util.FailResponse(constant.ERROR_CODE_1103, constant.ERROR_MESSAGE_1103))
		return
	}

	var param AddUserRequest
	if err = c.ShouldBindJSON(&param); err != nil {
		go_logger.Logger.Error(err.Error())
		c.JSON(http.StatusOK, util.FailResponse(constant.ERROR_CODE_1002, constant.ERROR_MESSAGE_1002))
		return
	}

	r := api.service.ModuleByName("MYSQLDB")
	if db, ok := r.(*module.MysqlDB); ok {

		// 检查手机号和邮箱是否唯一
		var count int
		err = db.Table(model.SysUserTable).Where("phone = ? and status != 3", param.Phone).Count(&count).Error
		if err != nil {
			go_logger.Logger.Error(err.Error())
			c.JSON(http.StatusOK, util.FailResponse(constant.ERROR_CODE_1002, constant.ERROR_MESSAGE_1002))
			return
		}
		if count > 0 {
			c.JSON(http.StatusOK, util.FailResponse(constant.ERROR_CODE_1003, "手机号已存在"))
			return
		}

		err = db.Table(model.SysUserTable).Where("email = ? and status != 3", param.Email).Count(&count).Error
		if err != nil {
			go_logger.Logger.Error(err.Error())
			c.JSON(http.StatusOK, util.FailResponse(constant.ERROR_CODE_1002, constant.ERROR_MESSAGE_1002))
			return
		}
		if count > 0 {
			c.JSON(http.StatusOK, util.FailResponse(constant.ERROR_CODE_1003, "邮箱已存在"))
			return
		}

		var user model.SysUser
		user.OrgId = param.OrgId
		user.OrgName = param.OrgName
		user.RoleId = param.RoleId
		user.UserName = param.UserName
		user.Nickname = param.Nickname
		user.Phone = param.Phone
		user.Email = param.Email
		user.Status = constant.USER_STATUS_USING
		var password = constant.DEFAULT_PASSWORD
		if param.UserPassword != "" {
			user.UserPassword = password
		}
		user.UserPassword = param.UserPassword
		user.CreateTime = time.Now()
		user.CreateUserName = util.ToString(userName)
		user.UpdateTime = time.Now()
		user.UpdateUserName = util.ToString(userName)

		err = db.Table(model.SysUserTable).Save(&user).Error
		if err != nil {
			go_logger.Logger.Error(err.Error())
			c.JSON(http.StatusOK, util.FailResponse(constant.ERROR_CODE_1001, constant.ERROR_MESSAGE_1001))
			return
		}

		c.JSON(http.StatusOK, util.SuccessResponse(nil))
		return
	}
}

type EditUserRequest struct {
	UserId   int    `form:"user_id" json:"user_id" binding:"required"`
	OrgId    int    `form:"org_id" json:"org_id"`
	OrgName  string `form:"org_name" json:"org_name"`
	RoleId   int    `form:"role_id" json:"role_id" binding:"required"`
	Nickname string `form:"nickname" json:"nickname"`
	Phone    string `form:"phone" json:"phone" binding:"required"`
	Email    string `form:"email" json:"email" binding:"required"`
}

// 编辑用户
func (api *HttpApi) EditUser(c *gin.Context) {
	userId, exist := c.Get("login_id")
	if !exist || userId == "" {
		c.JSON(http.StatusOK, util.FailResponse(constant.ERROR_CODE_1103, constant.ERROR_MESSAGE_1103))
		return
	}
	userName, exist := c.Get("login_name")
	if !exist || userName == "" {
		c.JSON(http.StatusOK, util.FailResponse(constant.ERROR_CODE_1103, constant.ERROR_MESSAGE_1103))
		return
	}

	var param EditUserRequest
	if err := c.ShouldBindJSON(&param); err != nil {
		go_logger.Logger.Error(err.Error())
		c.JSON(http.StatusOK, util.FailResponse(constant.ERROR_CODE_1002, constant.ERROR_MESSAGE_1002))
		return
	}

	r := api.service.ModuleByName("MYSQLDB")
	if db, ok := r.(*module.MysqlDB); ok {
		var user model.SysUser
		where := map[string]interface{}{
			"id": param.UserId,
		}
		err := db.Table(model.SysUserTable).Where(where).First(&user).Error
		if err != nil {
			go_logger.Logger.Error(err.Error())
			c.JSON(http.StatusOK, util.FailResponse(constant.ERROR_CODE_1001, constant.ERROR_MESSAGE_1001))
			return
		}

		user.Nickname = param.Nickname
		user.OrgId = param.OrgId
		user.OrgName = param.OrgName
		user.Phone = param.Phone
		user.Email = param.Email
		user.RoleId = param.RoleId
		user.UpdateTime = time.Now()
		user.UpdateUserName = util.ToString(userName)

		err = db.Table(model.SysUserTable).Save(&user).Error
		if err != nil {
			go_logger.Logger.Error(err.Error())
			c.JSON(http.StatusOK, util.FailResponse(constant.ERROR_CODE_1002, constant.ERROR_MESSAGE_1002))
			return
		}

		c.JSON(http.StatusOK, util.SuccessResponse(nil))
		return
	}
}

type EditMyselfRequest struct {
	UserName string `form:"user_name" json:"user_name"`
	Nickname string `form:"nickname" json:"nickname"`
	Phone    string `form:"phone" json:"phone" binding:"required"`
	Email    string `form:"email" json:"email" binding:"required"`
}

// 编辑个人信息
func (api *HttpApi) EditMyself(c *gin.Context) {
	var err error

	userId, exist := c.Get("login_id")
	if !exist || userId == "" {
		c.JSON(http.StatusOK, util.FailResponse(constant.ERROR_CODE_1103, constant.ERROR_MESSAGE_1103))
		return
	}
	userName, exist := c.Get("login_name")
	if !exist || userName == "" {
		c.JSON(http.StatusOK, util.FailResponse(constant.ERROR_CODE_1103, constant.ERROR_MESSAGE_1103))
		return
	}

	var param EditMyselfRequest
	if err = c.ShouldBindJSON(&param); err != nil {
		go_logger.Logger.Error(err.Error())
		c.JSON(http.StatusOK, util.FailResponse(constant.ERROR_CODE_1002, constant.ERROR_MESSAGE_1002))
		return
	}

	r := api.service.ModuleByName("MYSQLDB")
	if db, ok := r.(*module.MysqlDB); ok {

		// 检查手机号和邮箱是否唯一，且排除自己
		var count int
		err = db.Table(model.SysUserTable).Where("phone = ? and id != ? and status != 3", userId, param.Phone).Count(&count).Error
		if err != nil {
			go_logger.Logger.Error(err.Error())
			c.JSON(http.StatusOK, util.FailResponse(constant.ERROR_CODE_1002, constant.ERROR_MESSAGE_1002))
			return
		}
		if count > 0 {
			c.JSON(http.StatusOK, util.FailResponse(constant.ERROR_CODE_1003, "手机号已存在"))
			return
		}

		err = db.Table(model.SysUserTable).Where("email = ? and id != ? and status != 3", userId, param.Email).Count(&count).Error
		if err != nil {
			go_logger.Logger.Error(err.Error())
			c.JSON(http.StatusOK, util.FailResponse(constant.ERROR_CODE_1002, constant.ERROR_MESSAGE_1002))
			return
		}
		if count > 0 {
			c.JSON(http.StatusOK, util.FailResponse(constant.ERROR_CODE_1003, "邮箱已存在"))
			return
		}

		var user model.SysUser
		where := map[string]interface{}{
			"id": userId,
		}
		err := db.Table(model.SysUserTable).Where(where).First(&user).Error
		if err != nil {
			go_logger.Logger.Error(err.Error())
			c.JSON(http.StatusOK, util.FailResponse(constant.ERROR_CODE_1001, constant.ERROR_MESSAGE_1001))
			return
		}

		user.UserName = param.UserName
		user.Nickname = param.Nickname
		user.Phone = param.Phone
		user.Email = param.Email
		user.UpdateTime = time.Now()
		user.UpdateUserName = util.ToString(userName)

		err = db.Table(model.SysUserTable).Save(&user).Error
		if err != nil {
			go_logger.Logger.Error(err.Error())
			c.JSON(http.StatusOK, util.FailResponse(constant.ERROR_CODE_1002, constant.ERROR_MESSAGE_1002))
			return
		}

		c.JSON(http.StatusOK, util.SuccessResponse(nil))
		return
	}
}

// 冻结用户
func (api *HttpApi) FreezeUser(c *gin.Context) {
	userId, exist := c.Get("login_id")
	if !exist || userId == "" {
		c.JSON(http.StatusOK, util.FailResponse(constant.ERROR_CODE_1103, constant.ERROR_MESSAGE_1103))
		return
	}
	userName, exist := c.Get("login_name")
	if !exist || userName == "" {
		c.JSON(http.StatusOK, util.FailResponse(constant.ERROR_CODE_1103, constant.ERROR_MESSAGE_1103))
		return
	}

	freezeUserId := c.Query("user_id")

	r := api.service.ModuleByName("MYSQLDB")
	if db, ok := r.(*module.MysqlDB); ok {
		var user model.SysUser
		where := map[string]interface{}{
			"id": freezeUserId,
		}
		err := db.Table(model.SysUserTable).Where(where).First(&user).Error
		if err != nil {
			go_logger.Logger.Error(err.Error())
			c.JSON(http.StatusOK, util.FailResponse(constant.ERROR_CODE_1503, constant.ERROR_MESSAGE_1503))
			return
		}

		if user.Status != constant.USER_STATUS_USING {
			c.JSON(http.StatusOK, util.FailResponse(constant.ERROR_CODE_1503, constant.ERROR_MESSAGE_1503))
			return
		}

		user.Status = constant.NODE_STATUS_FREESE
		user.UpdateTime = time.Now()
		user.UpdateUserName = util.ToString(userName)

		err = db.Table(model.SysUserTable).Save(&user).Error
		if err != nil {
			go_logger.Logger.Error(err.Error())
			c.JSON(http.StatusOK, util.FailResponse(constant.ERROR_CODE_1503, constant.ERROR_MESSAGE_1503))
			return
		}

		c.JSON(http.StatusOK, util.SuccessResponse(nil))
		return
	}
}

// 解冻用户
func (api *HttpApi) UnFreezeUser(c *gin.Context) {
	userId, exist := c.Get("login_id")
	if !exist || userId == "" {
		c.JSON(http.StatusOK, util.FailResponse(constant.ERROR_CODE_1103, constant.ERROR_MESSAGE_1103))
		return
	}
	userName, exist := c.Get("login_name")
	if !exist || userName == "" {
		c.JSON(http.StatusOK, util.FailResponse(constant.ERROR_CODE_1103, constant.ERROR_MESSAGE_1103))
		return
	}

	unFreezeUserId := c.Query("user_id")

	r := api.service.ModuleByName("MYSQLDB")
	if db, ok := r.(*module.MysqlDB); ok {
		var user model.SysUser
		where := map[string]interface{}{
			"id": unFreezeUserId,
		}
		err := db.Table(model.SysUserTable).Where(where).First(&user).Error
		if err != nil {
			go_logger.Logger.Error(err.Error())
			c.JSON(http.StatusOK, util.FailResponse(constant.ERROR_CODE_1504, constant.ERROR_MESSAGE_1504))
			return
		}

		if user.Status != constant.USER_STATUS_FREESE {
			c.JSON(http.StatusOK, util.FailResponse(constant.ERROR_CODE_1504, constant.ERROR_MESSAGE_1504))
			return
		}

		user.Status = constant.NODE_STATUS_USING
		user.UpdateTime = time.Now()
		user.UpdateUserName = util.ToString(userName)

		err = db.Table(model.SysUserTable).Save(&user).Error
		if err != nil {
			go_logger.Logger.Error(err.Error())
			c.JSON(http.StatusOK, util.FailResponse(constant.ERROR_CODE_1503, constant.ERROR_MESSAGE_1503))
			return
		}

		c.JSON(http.StatusOK, util.SuccessResponse(nil))
		return
	}
}

// 删除用户
func (api *HttpApi) DeleteUser(c *gin.Context) {
	userId, exist := c.Get("login_id")
	if !exist || userId == "" {
		c.JSON(http.StatusOK, util.FailResponse(constant.ERROR_CODE_1103, constant.ERROR_MESSAGE_1103))
		return
	}
	userName, exist := c.Get("login_name")
	if !exist || userName == "" {
		c.JSON(http.StatusOK, util.FailResponse(constant.ERROR_CODE_1103, constant.ERROR_MESSAGE_1103))
		return
	}

	deleteUserId := c.Query("user_id")

	r := api.service.ModuleByName("MYSQLDB")
	if db, ok := r.(*module.MysqlDB); ok {
		var user model.SysUser
		where := map[string]interface{}{
			"id": deleteUserId,
		}
		err := db.Table(model.SysUserTable).Where(where).First(&user).Error
		if err != nil {
			go_logger.Logger.Error(err.Error())
			c.JSON(http.StatusOK, util.FailResponse(constant.ERROR_CODE_1503, constant.ERROR_MESSAGE_1506))
			return
		}

		user.Status = constant.NODE_STATUS_DELETE
		user.UpdateTime = time.Now()
		user.UpdateUserName = util.ToString(userName)

		err = db.Table(model.SysUserTable).Save(&user).Error
		if err != nil {
			go_logger.Logger.Error(err.Error())
			c.JSON(http.StatusOK, util.FailResponse(constant.ERROR_CODE_1503, constant.ERROR_MESSAGE_1506))
			return
		}

		c.JSON(http.StatusOK, util.SuccessResponse(nil))
		return
	}
}

// 用户列表
func (api *HttpApi) UserList(c *gin.Context) {

	var err error
	var users []*model.SysUser
	var result []*UserResponse

	pageStr := c.Query("page")
	pageSizeStr := c.Query("page_size")
	status := c.Query("status")
	param := c.Query("params")

	page, err := strconv.Atoi(pageStr)
	if err != nil {
		c.JSON(http.StatusOK, util.FailResponse(constant.ERROR_CODE_1003, "page 应为数字"))
		return
	}

	pageSize, err := strconv.Atoi(pageSizeStr)
	if err != nil {
		c.JSON(http.StatusOK, util.FailResponse(constant.ERROR_CODE_1003, "pageSize 应为数字"))
		return
	}

	r := api.service.ModuleByName("MYSQLDB")
	if db, ok := r.(*module.MysqlDB); ok {

		var count int
		var countDb = db.Table(model.SysUserTable)
		if len(status) > 0 {
			countDb = countDb.Where("status = ?", status)
		}
		if len(param) > 0 {
			countDb = countDb.Where("user_name like ? or email like ? or phone like ?", "%"+param+"%", "%"+param+"%", "%"+param+"%")
		}
		err = countDb.Count(&count).Error
		if err != nil {
			go_logger.Logger.Error(err.Error())
			c.JSON(http.StatusOK, util.FailResponse(constant.ERROR_CODE_1001, constant.ERROR_MESSAGE_1001))
			return
		}

		if count != 0 {
			var selectDb = db.Table(model.SysUserTable)
			if len(status) > 0 {
				selectDb = countDb.Where("status = ?", status)
			}
			if len(param) > 0 {
				countDb = countDb.Where("user_name like ? or email like ? or phone like ?", "%"+param+"%", "%"+param+"%", "%"+param+"%")
			}
			err = selectDb.Order("update_time desc").Limit(pageSize).Offset((page - 1) * pageSize).Find(&users).Error
			if err != nil {
				go_logger.Logger.Error(err.Error())
				c.JSON(http.StatusOK, util.FailResponse(constant.ERROR_CODE_1001, constant.ERROR_MESSAGE_1001))
				return
			}

			roleNameMap := map[int]string{}
			for _, user := range users {

				if _, ok := roleNameMap[user.RoleId]; !ok {
					var role model.SysRole
					err = db.Table(model.SysRoleTable).First(&role, user.RoleId).Error
					if err != nil {
						go_logger.Logger.Error(err.Error())
						c.JSON(http.StatusOK, util.FailResponse(constant.ERROR_CODE_1001, constant.ERROR_MESSAGE_1001))
						return
					}
					roleNameMap[user.RoleId] = role.RoleName
				}

				item := &UserResponse{}
				item.Id = user.Id
				item.UserName = user.UserName
				item.Nickname = user.Nickname
				item.Phone = user.Phone
				item.Email = user.Email
				item.Avatar = user.Avatar
				item.Status = user.Status
				item.RoleId = user.RoleId
				item.RoleName = roleNameMap[user.RoleId]
				item.OrgId = user.OrgId
				item.OrgName = user.OrgName
				item.Status = user.Status
				item.CreateTime = user.CreateTime.Format(constant.DATE_FORMAT)
				item.UpdateTime = user.UpdateTime.Format(constant.DATE_FORMAT)
				item.CreateUserName = user.CreateUserName
				item.UpdateUserName = user.UpdateUserName

				result = append(result, item)
			}
		}

		c.JSON(http.StatusOK, util.SuccessResponse(map[string]interface{}{
			"list":  result,
			"count": count,
		}))
		return
	}
}
